/*
 * @(#)View.java
 *
 * @author <a href="gubarevs@apollo.lv">Denis Gubarev</a>
 */

package com.gshappcore.presentation.view;

import com.google.gwt.dom.client.Document;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.gshappcore.model.ContextModel;
import com.gshappcore.model.Model;
import com.gshappcore.presentation.presenter.Presenter;

import java.util.ArrayList;
import java.util.List;

public abstract class View implements Redrawable {

    private final String id = getClass().getName();
    private Model model;
    private Presenter presenter;

    private final List<Redrawable> redrawables = new ArrayList<Redrawable>();

    private RootPanel mainPanel = RootPanel.get("scrollingContent");
    private VerticalPanel basePanel = new VerticalPanel();
    private VerticalPanel menuPanel = new VerticalPanel();
    private VerticalPanel violationHeaderPanel = new VerticalPanel();
    private VerticalPanel commonViewPanel = new VerticalPanel();

    public abstract void renderCommonView();

    public abstract Presenter createPresenter();

    public abstract Model createModel();

    public void init() {
        model = createModel();
        attachContext(model);
        presenter = createPresenter();

        basePanel.clear();
        basePanel.add(menuPanel);
        basePanel.add(violationHeaderPanel);
        basePanel.add(commonViewPanel);

        mainPanel.add(basePanel);

        renderCommonView();
    }

    private void attachContext(Model model) {
        final String url = Document.get().getURL();
        final String viewId = getId();
        new ContextModel(url, viewId).attachTo(model);
    }

    public final void redraw(Model newModel) {
        attachContext(newModel);

        updatePage(newModel);

        for (Redrawable redrawable : redrawables) {
            redrawable.redraw(newModel);
        }
    }

    public void destroy() {
        redrawables.clear();
    }

    protected void updatePage(Model newModel) {
    }

    public String getId() {
        return id;
    }

    public Model getModel() {
        return model;
    }

    public Presenter getPresenter() {
        return presenter;
    }

    public VerticalPanel getBasePanel() {
        return basePanel;
    }

    public VerticalPanel getMenuPanel() {
        return menuPanel;
    }

    public VerticalPanel getViolationHeaderPanel() {
        return violationHeaderPanel;
    }

    public VerticalPanel getCommonViewPanel() {
        return commonViewPanel;
    }

    public void updateCommonViewPanel(Panel panel) {
        commonViewPanel.clear();
        commonViewPanel.add(panel);
    }
}
